package dev.blogmoon.cn.system.repository;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import dev.blogmoon.cn.common.entity.PageResult;
import dev.blogmoon.cn.common.utils.BaseConvert;
import dev.blogmoon.cn.common.utils.PageUtil;
import dev.blogmoon.cn.system.entity.SysDict;
import dev.blogmoon.cn.system.entity.SysDictValue;
import dev.blogmoon.cn.system.module.QueryDictReq;
import dev.blogmoon.cn.system.module.SysDictDTO;
import dev.blogmoon.cn.system.service.SysDictService;
import dev.blogmoon.cn.system.service.SysDictValueService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class SysDictRepository {


    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private SysDictValueService sysDictValueService;

    public String getDictValue(String code, Object fieldValue) {
        SysDict sysDict = sysDictService.getOne(Wrappers.<SysDict>lambdaQuery().eq(SysDict::getCode, code));
        if (Objects.isNull(sysDict)) {
            return StringUtils.EMPTY;
        }
        SysDictValue sysDictValue = sysDictValueService.getOne(Wrappers.<SysDictValue>lambdaQuery().eq(SysDictValue::getDictId, sysDict.getId())
                .eq(SysDictValue::getName, fieldValue));
        return Objects.isNull(sysDictValue) ? StringUtils.EMPTY : sysDictValue.getValue();
    }

    public PageResult<SysDictDTO> page(QueryDictReq req) {

        Page<SysDict> page = sysDictService.page(new Page<>(req.getPageNo(), req.getPageSize()), Wrappers.<SysDict>lambdaQuery()
                .like(StringUtils.isNotBlank(req.getName()), SysDict::getName, req.getName())
                .eq(Objects.nonNull(req.getStatus()), SysDict::getStatus, req.getStatus())
                .orderByDesc(SysDict::getCreateTime));

        return PageUtil.getPage(page, item -> BaseConvert.convert(item, SysDictDTO.class));
    }

    public void save(SysDictDTO sysDictDTO) {
        SysDict sysDict = BaseConvert.convert(sysDictDTO, SysDict.class);
        if (Objects.isNull(sysDict.getId())) {
            sysDict.setModifyField();
            sysDictService.save(sysDict);
        } else {
            sysDict.setCreateField();
            sysDictService.updateById(sysDict);
        }
    }

    public void remove(List<Long> ids) {
        sysDictService.removeByIds(ids);
    }

    public SysDictDTO getById(Long id) {
        SysDict sysDict = sysDictService.getById(id);
        return BaseConvert.convert(sysDict, SysDictDTO.class);
    }
}
